using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.API.Models;
using System.Security.Claims;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("pingjia")]
    public class ReviewController : ControllerBase
    {
        private readonly IReviewService _reviewService;

        public ReviewController(IReviewService reviewService)
        {
            _reviewService = reviewService;
        }

        /// <summary>
        /// 获取评价列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<R>> GetReviews()
        {
            var reviews = await _reviewService.GetReviewsAsync();
            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = reviews
            });
        }

        /// <summary>
        /// 获取菜品评价列表
        /// </summary>
        [HttpGet("dish/{dishName}")]
        public async Task<ActionResult<R>> GetDishReviews(string dishName)
        {
            var reviews = await _reviewService.GetDishReviewsAsync(dishName);
            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = reviews
            });
        }

        /// <summary>
        /// 获取评价详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<R>> GetReview(long id)
        {
            var review = await _reviewService.GetReviewAsync(id);
            if (review == null)
            {
                return Ok(new R { code = 1, msg = "评价不存在" });
            }

            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = review
            });
        }

        /// <summary>
        /// 添加评价
        /// </summary>
        [Authorize]
        [HttpPost("add")]
        public async Task<ActionResult<R>> CreateReview([FromBody] Review model)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            model.userid = userId;
            var review = await _reviewService.CreateReviewAsync(model);

            return Ok(new R
            {
                code = 0,
                msg = "评价成功",
                data = review
            });
        }

        /// <summary>
        /// 修改评价
        /// </summary>
        [Authorize]
        [HttpPost("update")]
        public async Task<ActionResult<R>> UpdateReview([FromBody] Review model)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            var review = await _reviewService.GetReviewAsync(model.id);
            if (review == null)
            {
                return Ok(new R { code = 1, msg = "评价不存在" });
            }

            if (review.userid != userId && !User.IsInRole("Admin"))
            {
                return Ok(new R { code = 1, msg = "无权修改此评价" });
            }

            var updatedReview = await _reviewService.UpdateReviewAsync(model);
            return Ok(new R
            {
                code = 0,
                msg = "修改成功",
                data = updatedReview
            });
        }

        /// <summary>
        /// 删除评价
        /// </summary>
        [Authorize]
        [HttpPost("delete/{id}")]
        public async Task<ActionResult<R>> DeleteReview(long id)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            var review = await _reviewService.GetReviewAsync(id);
            if (review == null)
            {
                return Ok(new R { code = 1, msg = "评价不存在" });
            }

            if (review.userid != userId && !User.IsInRole("Admin"))
            {
                return Ok(new R { code = 1, msg = "无权删除此评价" });
            }

            await _reviewService.DeleteReviewAsync(id);
            return Ok(new R { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 回复评价
        /// </summary>
        [Authorize(Roles = "Admin")]
        [HttpPost("reply/{id}")]
        public async Task<ActionResult<R>> ReplyReview(long id, [FromBody] ReviewReplyModel model)
        {
            var review = await _reviewService.ReplyReviewAsync(id, model.Reply);
            if (review == null)
            {
                return Ok(new R { code = 1, msg = "评价不存在" });
            }

            return Ok(new R
            {
                code = 0,
                msg = "回复成功",
                data = review
            });
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        [HttpGet("page")]
        public async Task<ActionResult<R>> GetReviewsPage([FromQuery] PageParams queryParams)
        {
            var reviews = await _reviewService.GetReviewsAsync();
            
            // 应用分页
            var pagedReviews = reviews
                .Skip((queryParams.PageNumber - 1) * queryParams.PageSize)
                .Take(queryParams.PageSize)
                .ToList();
                
            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = new ReviewPageUtils
                {
                    list = pagedReviews,
                    totalCount = reviews.Count(),
                    pageSize = queryParams.PageSize,
                    currPage = queryParams.PageNumber,
                    totalPage = (int)Math.Ceiling(reviews.Count() / (double)queryParams.PageSize)
                }
            });
        }
    }

    public class ReviewReplyModel
    {
        public string Reply { get; set; }
    }
} 